package rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 声明组件 springboot整理需要配置类 定义bean对象@Bean
 */
@Configuration
@Slf4j
public class DeclareConfig {
    //声明 队列 名字 demo-queue 持久化 不专属 不自动删除 没有特性属性
    //channel.queueDeclare("demo-queue",true,false,false,null);
    @Bean
    public Queue declareQueue(){
        //第一种写法 直接new Queue
        //return new Queue("demo-queue",true,false,false,null);
        //第二种 调用构建工具builder
        return QueueBuilder.nonDurable("demo-queue").withArgument("x-message-ttl",10000).build();
    }
    //交换机
    @Bean
    public Exchange declareFanoutEx(){
        //第一种写发 直接new
        //return new FanoutExchange("demo-ex");
        //第二种写法 调用builder
        return ExchangeBuilder.fanoutExchange("demo-ex").build();
    }
    //绑定关系 Binding BindingBuilder 最后没有build() noargs()
    @Bean
    public Binding declareBinding(){
        //第一种 new Binding();
        //第二种 builder
        return BindingBuilder.
                bind(declareQueue()).
                to(declareFanoutEx()).
                with("demo-rk").noargs();
    }

    //业务交换机名字
    public static final String BIZ_EX="biz_ex";
    //业务队列名字
    public static final String BIZ_QUEUE="biz_queue";
    //死信交换机名字
    public static final String DLX_EX="dlx_ex";
    //死信队列名字
    public static final String DLX_QUEUE="dlx_queue";
    //死信路由key
    public static final String DLX_ROUTING_KEY="dlx_routing_key";
    @Bean
    public Queue bizQueue(){
        return QueueBuilder.nonDurable(BIZ_QUEUE)
                .withArgument("x-message-ttl",20000)
                .withArgument("x-dead-letter-exchange",DLX_EX)
                .withArgument("x-dead-letter-routing-key",DLX_ROUTING_KEY).build();
    }
    //声明死信队列
    @Bean
    public Queue dlxQueue(){
        return QueueBuilder.nonDurable(DLX_QUEUE).build();
    }
    //业务交换机 fanout
    @Bean
    public Exchange bizEx(){
        return ExchangeBuilder.fanoutExchange(BIZ_EX).build();
    }
    //死信交换机 direct
    @Bean
    public Exchange dlxEx(){
        return ExchangeBuilder.directExchange(DLX_EX).build();
    }
    //业务队列和业务交换机绑定
    @Bean
    public Binding bizBinding(){
        return BindingBuilder.bind(bizQueue()).to(bizEx()).with("").noargs();
    }
    //死信队列和死信交换机绑定
    @Bean
    public Binding dlxBinding(){
        return BindingBuilder.bind(dlxQueue()).to(dlxEx()).with(DLX_ROUTING_KEY).noargs();
    }
}
